package com.example.aitasks.service;

import com.example.aitasks.model.TaskConfig;
import com.example.aitasks.model.TaskResult;
import com.example.aitasks.repo.TaskConfigRepository;
import com.example.aitasks.repo.TaskResultRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TaskRunnerService {
    private final TaskConfigRepository configRepo;
    private final TaskResultRepository resultRepo;
    private final FetchService fetchService;
    private final AiService aiService;

    public TaskRunnerService(TaskConfigRepository configRepo, TaskResultRepository resultRepo, FetchService fetchService, AiService aiService) {
        this.configRepo = configRepo;
        this.resultRepo = resultRepo;
        this.fetchService = fetchService;
        this.aiService = aiService;
    }

    @Scheduled(fixedDelay = 60000) // poll every minute
    public void pollAndRun() {
        List<TaskConfig> tasks = configRepo.findAll();
        LocalDateTime now = LocalDateTime.now();
        for (TaskConfig t : tasks) {
            if (Boolean.FALSE.equals(t.getEnabled())) continue;
            LocalDateTime next = t.getLastRunAt() == null ? now.minusMinutes(10) : t.getLastRunAt().plusMinutes(t.getIntervalMinutes() == null ? 60 : t.getIntervalMinutes());
            if (!next.isAfter(now)) {
                runOnce(t.getId());
            }
        }
    }

    @Transactional
    public TaskResult runOnce(Long taskId) {
        TaskConfig t = configRepo.findById(taskId).orElseThrow();
        TaskResult r = new TaskResult();
        r.setTaskId(taskId);
        r.setRunAt(LocalDateTime.now());
        try {
            String raw = fetchService.fetchText(t.getFetchUrl());
            r.setRawInput(raw);

            String sys = "You are an analyst. Always output STRICT JSON with keys: summary (string), key_points (string[]), entities (string[]), sentiment (one of: positive, neutral, negative). No markdown.";
            String user = "Task type: " + t.getType()
                    + "\nKeywords: " + (t.getKeywords() == null ? "" : t.getKeywords())
                    + "\nPlease analyze the following text and produce the JSON schema described above. Text:\n"
                    + raw;

            String aiJson = aiService.summarizeToJson(t.getModel(), sys, user);
            r.setAiOutputJson(aiJson);

            t.setLastRunAt(LocalDateTime.now());
            t.setLastStatus("SUCCESS");
            t.setLastSummary(aiJson.length() > 300 ? aiJson.substring(0, 300) + "..." : aiJson);
            configRepo.save(t);
        } catch (Exception ex) {
            r.setError(ex.getMessage());
            t.setLastRunAt(LocalDateTime.now());
            t.setLastStatus("ERROR");
            t.setLastSummary(ex.getMessage());
            configRepo.save(t);
        }
        return resultRepo.save(r);
    }
}
